package com.cershy.linyuminiserver.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.cershy.linyuminiserver.annotation.TimeRecord;
import com.cershy.linyuminiserver.annotation.UrlFree;
import com.cershy.linyuminiserver.annotation.UrlLimit;
import com.cershy.linyuminiserver.annotation.Userid;
import com.cershy.linyuminiserver.common.property.FileUploadProperties;
import com.cershy.linyuminiserver.service.SimpleFileService;
import com.cershy.linyuminiserver.utils.HttpFileUploadUtils;
import com.cershy.linyuminiserver.utils.ResultUtil;
import com.cershy.linyuminiserver.vo.file.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/file")
@RequiredArgsConstructor
@Slf4j
public class FileController {

    @Resource
    SimpleFileService simpleFileService;

    private final FileUploadProperties fileUploadProperties;

    private static final String LINUX_SEPARATOR = "/";

    /**
     * 发送offer
     */
    @UrlLimit
    @PostMapping("/offer")
    public JSONObject offer(@Userid String userId, @RequestBody OfferVo offerVo) {
        boolean result = simpleFileService.offer(userId, offerVo);
        return ResultUtil.ResultByFlag(result);
    }

    /**
     * 发送answer
     */
    @UrlLimit
    @PostMapping("/answer")
    public JSONObject answer(@Userid String userId, @RequestBody AnswerVo answerVo) {
        boolean result = simpleFileService.answer(userId, answerVo);
        return ResultUtil.ResultByFlag(result);
    }

    /**
     * 发送candidate
     */
    @UrlLimit
    @PostMapping("/candidate")
    public JSONObject candidate(@Userid String userId, @RequestBody CandidateVo candidateVo) {
        boolean result = simpleFileService.candidate(userId, candidateVo);
        return ResultUtil.ResultByFlag(result);
    }

    /**
     * 取消
     */
    @UrlLimit
    @PostMapping("/cancel")
    public JSONObject hangup(@Userid String userId, @RequestBody CancelVo cancelVo) {
        boolean result = simpleFileService.cancel(userId, cancelVo);
        return ResultUtil.ResultByFlag(result);
    }

    /**
     * 邀请
     */
    @UrlLimit
    @PostMapping("/invite")
    public JSONObject invite(@Userid String userId, @RequestBody InviteVo inviteVo) {
        boolean result = simpleFileService.invite(userId, inviteVo);
        return ResultUtil.ResultByFlag(result);
    }

    /**
     * 同意
     */
    @UrlLimit
    @PostMapping("/accept")
    public JSONObject accept(@Userid String userId, @RequestBody AcceptVo acceptVo) {
        boolean result = simpleFileService.accept(userId, acceptVo);
        return ResultUtil.ResultByFlag(result);
    }

    @UrlFree
    @PostMapping("/images/upload")
    @TimeRecord
    public Object uploadImage(@RequestParam("files") MultipartFile[] files) {
        System.out.println("文件上传开始"+ LocalDateTimeUtil.now());
        // 文件非空判断
        if (files == null||files.length==0) {
            return ResultUtil.Fail("文件上传失败,文件为空");
        }

        List<String> paths = new ArrayList<>();
        try {
            for(MultipartFile file : files){
                // 校验上传的文件类型
                //HttpFileUploadUtils.checkUploadImageType(file, uploadImageCheckTypes);
                //文件大小限制
                long fileSize = file.getSize() / 1024 / 1024;
                if (fileSize > 300) {
                    return ResultUtil.Fail("文件大小大于50M,上传错误");
                }

                String fileName = IdUtil.simpleUUID();
                String originalFilename = file.getOriginalFilename();
                String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String today = sdf.format(new Date());
                //http上传
                String dest = fileUploadProperties.getPath() + File.separator + today;
                String httpFileName = fileName + fileExt;
                HttpFileUploadUtils.httpUpload(file, dest, httpFileName);
                paths.add(LINUX_SEPARATOR + today + LINUX_SEPARATOR + httpFileName);
            }
        } catch (RuntimeException e) {
            log.warn("文件上传异常，请稍后再试：", e);
            throw e;
        } catch (Exception e) {
            log.error("文件上传异常，请稍后再试", e);
            throw new RuntimeException("文件上传异常，请稍后再试。");
        }
        System.out.println("文件上传结束"+ LocalDateTimeUtil.now());
        return ResultUtil.Succeed(paths);
    }
}
